package com.xauto.pioneer.appuser.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xauto.pioneer.appuser.MyApplication;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.mine.balance.AccountTopUpActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.util.ActivityStackManager;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.PromptDialog;

import net.tsz.afinal.FinalActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;

/**
 *
 * @author: Created by Lemon on 2014年6月21日 下午3:24:14
 * @Description: 所有Activity的基类
 */
public abstract class BaseActivity extends FinalActivity {

	protected Context mContext;

	public ImageLoader imageLoader;
	/** 请求获取成功标石*/
	protected static final int SUCCESS = 100;
	/** 请求获取失败标石*/
	protected static final int FAILURE = 200;
	/** 打印标签*/
	protected static String TAG = "TAG";
	protected BaseLHttpHandler lHandler;

	protected int page = Constants.PAGE;

	protected boolean isMore = true;
	/** 是否到最后一页*/
	protected boolean isOver = false;
	/** 是否是下拉刷新，清空数据*/
	protected boolean isPull = false;
	protected String token;
	protected String memberId;
	protected String Adrs="";
	protected String memberName;
	protected String avatar;
	protected String signature;
	protected String memberGroupId;
	protected String memberAdd="";
	String LinkRout="";
	String LinkValue="";
	String LinkValue2="";
	int LinkAccount;
	/** 控制软键盘*/
	protected InputMethodManager inputMethodManager;
	/**推送*/
	private PromptDialog promptDialog;

//	/** 收回所有刷新组件*/
//	protected void refreshComplete(RefreshListView listView) {
//		listView.onRefreshComplete();
//		listView.onLoadMoreComplete();
//	}

	/** 将刷新标石归置最初状态，即第一页并且可加载更多*/
	protected void refreshStatusInit() {
		page = Constants.PAGE;
		isPull = true;
		isOver = false;
	}

	/** 将刷新标石设为将在更多状态*/
	protected void refreshStatusNext() {
		page++;
		isPull = false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		//定义全屏参数
//		int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
//		//获得当前窗体对象
//		Window window = this.getWindow();
//		//设置当前窗体为全屏显示
//		window.setFlags(flag, flag);
		ActivityStackManager.getActivityManager().push(this);
		mContext = this;
		TAG = mContext.getClass().getSimpleName();

		/** 存储常用个人信息至缓存*/
		token = PreferencesUtils.getString(mContext, Constants.KEY_TOKEN);
		memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
		Adrs= PreferencesUtils.getString(mContext,"ADR");
		imageLoader = ImageLoader.getInstance();
//		memberName = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_NAME);
//		signature = PreferencesUtils.getString(mContext, Constants.KEY_SIGNATURE);
//		memberGroupId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_GROUP_ID, Constants.ROLE_GOOD_PERSON);

//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//			setTranslucentStatus(true);
//			SystemBarTintManager tintManager = new SystemBarTintManager(this);
//			tintManager.setStatusBarTintEnabled(true);
//			tintManager.setStatusBarTintResource(R.color.transparent);//通知栏所需颜色
//		}

		setContentView(getContentView());

		ButterKnife.bind(this);

		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initView();
		initData();
		registerMessageReceiver();
	}

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	/***
	 * login status
	 * @return true-login_success | false-no login_success
	 */
	protected boolean isLoginSuccess() {
		if(!StringUtils.isBlank(PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID))
				&&!StringUtils.isBlank(PreferencesUtils.getString(mContext, Constants.KEY_TOKEN))) {
			return true;
		}
		return false;
	}

	/***
	 * TOAST
	 * @param msg
	 */
	protected void prompt(String msg) {
		if(mContext != null) {
			ToastUtil.showShort(mContext, msg);
		}
	}
	/***
	 * TOAST
	 * @param StringId
	 */
	protected void prompt(int StringId) {
        if(mContext != null) {
            Toast.makeText(mContext, StringId, Toast.LENGTH_SHORT).show();
        }
    }

    protected String getResString(int StringId) {
        return mContext.getResources().getString(StringId);
    }

    /***
     * 公共解析
     * @param t
     * @return 完整json
     */
    protected JSONObject BaseJsonData(String t) {
        JSONObject object = null;
        try {
            object = new JSONObject(t);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

//	@Override
//	public final void startActivity(Intent intent) {
//		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//				| Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		super.startActivity(intent);
//	}

	/** 隐藏软键盘*/
	protected void hideSoftKeyboard() {
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/***
	 * 修改部分文本字体颜色
	 * @param text :需要修改的文本整体字段
	 * @param color :色值
	 * @param startIndex :需要修改的文字开始下标
	 * @param endIndex :需要修改的文字结束下标
	 * @param isForeground :true->设置文本前景颜色  | false->设置背景文本背景颜色
	 * @return
	 */
	protected SpannableStringBuilder ModifyTextpartColor(String text, int color, int startIndex, int endIndex, Boolean isForeground) {
		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		if(isForeground) {
			ForegroundColorSpan span= new ForegroundColorSpan(color);
			builder.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}else{
			BackgroundColorSpan span= new BackgroundColorSpan(color);
			builder.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return builder;
	}

	/**
	 * 时间计数器，最多只能到99小时，如需要更大小时数需要改改方法
	 * @param time
	 * @return
	 */
	protected String showTimeCount(long time) {
		System.out.println("time=" + time);
		if (time >= 360000000) {
			return "00:00:00";
		}
		String timeCount = "";
		long hourc = time / 3600000;
		String hour = "0" + hourc;
		System.out.println("hour=" + hour);
		hour = hour.substring(hour.length() - 2, hour.length());
		System.out.println("hour2=" + hour);

		long minuec = (time - hourc * 3600000) / (60000);
		String minue = "0" + minuec;
		System.out.println("minue=" + minue);
		minue = minue.substring(minue.length() - 2, minue.length());
		System.out.println("minue2=" + minue);

		long secc = (time - hourc * 3600000 - minuec * 60000) / 1000;
		String sec = "0" + secc;
		System.out.println("sec=" + sec);
		sec = sec.substring(sec.length() - 2, sec.length());
		System.out.println("sec2=" + sec);
		timeCount = hour + ":" + minue + ":" + sec;
		System.out.println("timeCount=" + timeCount);
		return timeCount;
	}

	protected void onResume() {
		super.onResume();
//		MobclickAgent.onResume(this);
	}
	protected void onPause() {
		super.onPause();
//		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mMessageReceiver);
	}

	protected abstract int getContentView();
	/**
	 * 初始化UI控件
	 */
	protected abstract void initView();
	/**
	 * 初始化数据
	 */
	protected abstract void initData();


	private boolean isQuit = false;
	private Timer timer = new Timer();

	public boolean KeyBackQuit(int keyCode) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isQuit == false) {
				isQuit = true;
				Toast.makeText(getBaseContext(), getResString(R.string.text_quit),
						Toast.LENGTH_SHORT).show();
				TimerTask task = null;
				task = new TimerTask() {
					@Override
					public void run() {
						isQuit = false;
					}
				};
				timer.schedule(task, 2000);
			} else {
				ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
				manager.killBackgroundProcesses(getPackageName());
				finish();
//				System.exit(0);
			}
		}
		return isQuit;
	}
	//-------------------极光推送------------------------
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.xauto.pioneer.appuser.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}
	public class MessageReceiver extends BroadcastReceiver {

		@SuppressLint("SimpleDateFormat")
		@Override
		public void onReceive(Context context, Intent intent) {

				String message = intent.getStringExtra(KEY_MESSAGE);
				String extras = intent.getStringExtra(KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(KEY_MESSAGE + " : " + message + "\n");
			Log.e("tag",KEY_MESSAGE + " : " + message + "\n");
			Log.e("tag",KEY_EXTRAS + " : " + extras + "\n");
				try {
					JSONObject jsonMessage = new JSONObject(extras);
					LinkRout = jsonMessage.getString("link_route");
					LinkValue = jsonMessage.getString("link_value");
					JSONObject jsonAccount = new JSONObject(LinkValue);
					LinkValue2 = jsonAccount.getString("link_value");
					LinkAccount = jsonAccount.getInt("mix_total_amount");
					Log.e("tag", LinkAccount + "\n");
					PushDialong(LinkValue2, LinkRout,LinkAccount);
				} catch (JSONException e) {
					e.printStackTrace();// 异常处理
				}
		}

		private void PushDialong(String Message, String Key, final int account) {
			if(Key.equals("warning_credit_amount")){
			MyApplication.getInstance().mSpeechSynthesizer.speak("您的车辆信用使用金额已不足，请尽快充值，而不影响您继续使用车辆，谢谢您的支持。");}
			if(Key.equals("beyond_credit_amount")){
				MyApplication.getInstance().mSpeechSynthesizer.speak("您的车辆信用使用金额已超，请尽快充值，而不影响您继续使用车辆，谢谢您的支持。");}
			if (promptDialog != null){
				if (promptDialog.isShowing())
					promptDialog.cancel();
				promptDialog = null;
			}

			promptDialog = new PromptDialog(mContext, getString(R.string.carNotice), Message,
					getString(R.string.recharge),getString(R.string.cancel),getString(R.string.dialogpic_notice), new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//去充值
					Intent intent = new Intent(mContext, AccountTopUpActivity.class);
					intent.putExtra("accountnum",account);
					startActivity(intent);
					promptDialog.dismiss();
				}
			}, new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//确定
					promptDialog.dismiss();
				}
			});
			promptDialog.show();
		}
	}}